package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.BaseServiceImpl;
import com.usian.common.constants.wemedia.WemediaConstants;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WmNewsServiceImpl extends BaseServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String basePath;

    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;

    @Autowired
    private WmMaterialMapper materialMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto == null) return errorResult;
        Integer userId = WmThreadLocalUtils.getUserId();
        if (userId == null) return errorResult;
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getUserId, userId);
        if (dto.getStatus() != null) wrapper.eq(WmNews::getStatus, dto.getStatus());
        if (dto.getChannelId() != null) wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        if (dto.getKeyword() != null) wrapper.like(WmNews::getTitle, dto.getKeyword());
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null)
            wrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        Page<WmNews> page = new Page<>(dto.page, dto.size);
        IPage<WmNews> resultPage = page(page, wrapper);
        ResponseResult result = new PageResponseResult(dto.page, dto.size, (int) resultPage.getTotal());
        result.setData(resultPage.getRecords());
        result.setHost(basePath);
        return result;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
        boolean isSuccess = false;
        if (wmNews == null || wmNews.getContent().isEmpty()) return errorResult;
        WmNews news = new WmNews();
        //将前端传过来的内容赋值到要保存到表里的对象
        BeanUtils.copyProperties(wmNews, news);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())) {
            news.setType(null);
        }
        if (wmNews.getImages() != null && wmNews.getImages().size() != 0) {
            StringBuffer buffer = new StringBuffer();
            wmNews.getImages().forEach(s -> buffer.append(s.replace(basePath, "")).append(","));
            news.setImages(buffer.toString().substring(0, buffer.toString().length() - 1));
        }
        news.setStatus(isSubmit);
        Integer userId = WmThreadLocalUtils.getUserId();
        news.setUserId(userId);
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        news.setEnable((short) 1);
        //对象字段赋值完成后，还有两件事1，确定素材和新闻的关系 2，保存新闻
        if (news.getId() == null) {//以前没有这个文章，新增文章
            isSuccess = save(news);
        } else {//有id说明是修改文章
            //删除关系表中新闻和素材的关系数据。
            newsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, news.getId()));
            //更新修改的内容
            isSuccess = updateById(news);
        }
        //将前端传过来的新闻内容中的资源提取出来保存到集合中
        String content = wmNews.getContent();
        List<String> materialList = new ArrayList<>();
        JSONArray array = JSON.parseArray(content);
        array.forEach(m -> {
            JSONObject object = JSON.parseObject(m.toString());
            if (object.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                materialList.add(object.get("value").toString().replace(basePath, ""));
            }
        });
        // WmNews.Status.SUBMIT.getCode()=1
        // 如果状态是提交，且文件内容中有资源引用
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            if (materialList.size() != 0) { // 保存文章内容中素材和新闻的关系
                ResponseResult responseResult = saveRelativeInfoForContent(materialList, news.getId());
                if (responseResult != null) {
                    return responseResult;
                }
            }
            // 保存封面资源和新闻的关系数据
            ResponseResult responseResult = saveRelativeInfoForCover(wmNews, materialList, news);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    /*
    保存封面资源和新闻的关系数据
    Wmnews : 前端传过来的新闻对象
    materialList : 包含所有详情内容资源路径的集合
    wmNews1 : 要更新或保存到表里的新闻对象
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto wmNews, List<String> materialList, WmNews wmNews1) {
        // 前端传过来的封面图集合
        List<String> images = wmNews.getImages();
        // 如果前端在提交数据时封面选择的是自动
        if (wmNews.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            if (materialList.size() == 0) { // 无图模式

            }else if (materialList.size() <=2){ // 单图模式

            }else { // 多图模式

            }
        }
        return null;
    }

    /**
     * 保存素材与文章内容的关系
     *
     * @param
     * @param
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materialList, Integer id) {
        return saveRelativeInfo(materialList, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }
    /*
    materialList :内容中引用的资源集合
    id : 新闻id
    wmContentReference : 引用类型，当前内容引用
    */

    private ResponseResult saveRelativeInfo(List<String> materialList, Integer id, Short wmContentReference) {
        List<WmMaterial> list = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materialList)); // 素材对象集合
        if (list == null || list.size() == 0) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "资源错误");
        List<String> IdList = new ArrayList<>();
        list.forEach(l -> IdList.add(l.getId().toString()));
        newsMaterialMapper.saveRelationsByContent(IdList, id, wmContentReference);
        return null;
    }

}
